package com.store.satring.web;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.joda.time.format.DateTimeFormat;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.store.satring.dos.Customer;
import com.store.satring.dos.Invoice;
import com.store.satring.dos.Item;
import com.store.satring.dos.ItemReport;
import com.store.satring.dos.ItemType;
import com.store.satring.utils.ReportUtils;
import com.store.satring.utils.StoreUtility;

@RequestMapping("/itemreports")
@Controller
public class ItemReportController {

	private final static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(
			"yyyy-MM-dd");

	@RequestMapping(method = RequestMethod.POST, produces = "text/html")
	public String create(@Valid ItemReport itemReport,
			BindingResult bindingResult, Model uiModel,
			HttpServletRequest httpServletRequest, HttpServletResponse response) {
		try {

			String reportName = "";
			Map<String, Object> parameters = new HashMap<String, Object>();
			if (itemReport.getShowOnlyStoreInventory()) {
				reportName = "StoreItemDetailReport";
			}else{
				reportName = "CustomerItemDetailReport";
				Date invoiceDateFrom = itemReport.getInvoiceDateFrom();
				Date invoiceDateTo = itemReport.getInvoiceDateTo();
				parameters.put("INVOICE_DATE_FROM", invoiceDateFrom == null ? null : getFormattedDate(invoiceDateFrom));
				parameters.put("INVOICE_DATE_TO", invoiceDateTo == null ? null : getFormattedDate(invoiceDateTo));

				List<Invoice> invoices = itemReport.getInvoices();
				String invoicePValue = "-1";
				if(invoices != null && invoices.size() > 0){
					invoicePValue = "";
					for (Invoice invoice : invoices) {
						invoicePValue += invoice.getId() +","; 
					}
					invoicePValue = invoicePValue.substring(0, invoicePValue.length()-1);
				}
				
				List<Customer> customers = itemReport.getCustomers();
				String customerPValue = "-1";
				if(customers != null && customers.size() > 0){
					customerPValue = "";
					for (Customer customer : customers) {
						customerPValue += customer.getId() + ",";
					}
					customerPValue = customerPValue.substring(0, customerPValue.length() -1);
				}
				
				List<ItemType> itemTypes = itemReport.getItemTypes();
				String itemTypePValue = "-1";
				if(itemTypes != null && itemTypes.size() > 0){
					itemTypePValue = "";
					for (ItemType itemType : itemTypes) {
						itemTypePValue += itemType.getId() + ",";
					}
					itemTypePValue = itemTypePValue.substring(0, itemTypePValue.length()-1);
				}
				
				List<Item> items = itemReport.getItems();
				String itemPValue = "-1";
				if(items != null && items.size() > 0){
					itemPValue = "";
					for (Item item : items) {
						itemPValue += item.getId() + ",";
					}
					itemPValue = itemPValue.substring(0, itemPValue.length() -1);
				}
				
				parameters.put("INVOICES", invoicePValue);
				parameters.put("CUSTOMERS", customerPValue);
				parameters.put("ITEM_TYPES", itemTypePValue);
				parameters.put("ITEMS", itemPValue);
			}

			ReportUtils reportUtils = new ReportUtils(reportName,
					parameters, response, httpServletRequest
							.getSession().getServletContext());
			boolean isReportGenerated = reportUtils.executeReport();

			if (!isReportGenerated) {
				bindingResult.reject("no_data_found", "No Data Found");
			}

		} catch (Exception e) {
			String exceptionMessage = StoreUtility.getRouteCauseMessage(e);
			bindingResult.reject("error_occured", "Exception Message : "
					+ exceptionMessage);

		}
		if (bindingResult.hasErrors()) {
			populateEditForm(uiModel, itemReport);
			return "itemreports/create";
		}
		uiModel.asMap().clear();
		return null;
	}

	@RequestMapping(params = "form", produces = "text/html")
	public String createForm(Model uiModel) {
		populateEditForm(uiModel, new ItemReport());
		return "itemreports/create";
	}

	void addDateTimeFormatPatterns(Model uiModel) {
		uiModel.addAttribute(
				"itemReport_invoicedatefrom_date_format",
				DateTimeFormat.patternForStyle("M-",
						LocaleContextHolder.getLocale()));
		uiModel.addAttribute(
				"itemReport_invoicedateto_date_format",
				DateTimeFormat.patternForStyle("M-",
						LocaleContextHolder.getLocale()));
	}

	void populateEditForm(Model uiModel, ItemReport itemReport) {
		uiModel.addAttribute("itemReport", itemReport);
		addDateTimeFormatPatterns(uiModel);
		uiModel.addAttribute("customers", Customer.findAllCustomers());
		uiModel.addAttribute("invoices", Invoice.findAllInvoices());
		uiModel.addAttribute("items", Item.findAllItems());
		uiModel.addAttribute("itemtypes", ItemType.findAllItemTypes());
	}
	
	private String getFormattedDate(Date date) {
		String formatedDate = DATE_FORMAT.format(date);
		return formatedDate;
	}

}
